package web.eshop;

import domain.shop.Category;
import domain.shop.Product;
import org.apache.wicket.Component;
import org.apache.wicket.PageParameters;
import org.apache.wicket.RestartResponseException;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.LoadableDetachableModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.wicketstuff.annotation.mount.MountPath;
import org.wicketstuff.annotation.strategy.MountIndexedParam;
import service.facade.customer.ShopCustomerService;
import web.eshop.panels.CategoryTreePanel;
import web.eshop.panels.ProductPanel;

import javax.swing.tree.DefaultMutableTreeNode;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.logging.Logger;

/**
 * Default eshop page. Display all products in selected category.
 */
@MountPath(path = "category")
@MountIndexedParam
public final class MultipleProductsEshopPage extends ShopBasePage {
    private static Logger logger = Logger.getLogger(MultipleProductsEshopPage.class.getName());

    @SpringBean
    private ShopCustomerService shopCustomerService;
    private final IModel<List<Product>> productsModel;
    CategoryTreePanel categoryTreePanel;
    Long categoryId;
    private IModel<Category> categoryModel;

    public MultipleProductsEshopPage() {
        //TODO OMEZIT POCET NACITANEJCH PRODUKTU
        productsModel = loadProductModel();
        initProductList(productsModel);
    }

    @Override
    protected Component newLeftPanel(String id) {
        categoryTreePanel = new CategoryTreePanel(id);
        if (categoryId != null) {
            DefaultMutableTreeNode node = findSelectedNode(categoryId);
            if (node != null) {
                if (node.isLeaf()) {
                    categoryTreePanel.getLinkTree().getTreeState().expandNode(node.getParent());
                } else {
                    categoryTreePanel.getLinkTree().getTreeState().expandNode(node);
                }
                categoryTreePanel.getLinkTree().getTreeState().selectNode(node, true);
                categoryTreePanel.getLinkTree().updateTree();
            } else {
                logger.severe("Nastala neocekavana chyba!! - MultipleProductsEshopPage - 54");
            }
        }


        return categoryTreePanel;
    }

    public MultipleProductsEshopPage(PageParameters params) {
        try {
            categoryId = params.getAsLong("0");
            categoryModel = new LoadableDetachableModel<Category>() {
                @Override
                protected Category load() {
                    return shopCustomerService.findCategoryById(categoryId);
                }
            };
            if (categoryModel.getObject() == null) throw new Exception("kategorie nenalezena");

            productsModel = loadProductModel(categoryId);

            initProductList(productsModel);
        } catch (Exception e) {
            setRedirect(true);
            throw new RestartResponseException(MultipleProductsEshopPage.class);

        }

    }

    private DefaultMutableTreeNode findSelectedNode(Long categoryId) {
        String wantedString = shopCustomerService.findCategoryById(categoryId).toString();
        DefaultMutableTreeNode root =
                (DefaultMutableTreeNode) categoryTreePanel.getLinkTree().getModelObject().getRoot();
        return findString(root, wantedString);
    }

    private DefaultMutableTreeNode findString(DefaultMutableTreeNode node, String wantedString) {
        DefaultMutableTreeNode tmp = null;
        for (Enumeration<DefaultMutableTreeNode> e = node.children(); e.hasMoreElements();) {
            tmp = e.nextElement();
            if (tmp.toString().equals(wantedString)) {
                return tmp;
            } else {
                DefaultMutableTreeNode tmp2 = findString(tmp, wantedString);
                if (tmp2 != null) {
                    return tmp2;
                }
            }
        }
        return null;
    }

    private void initProductList(IModel<List<Product>> productsModel) {
        add(new ListView<Product>("productList", productsModel) {

            @Override
            protected void populateItem(final ListItem<Product> item) {
                item.add(new ProductPanel("showProductPanel", item));
            }
        });
    }

    private LoadableDetachableModel<List<Product>> loadProductModel() {
        return new LoadableDetachableModel<List<Product>>() {

            @Override
            protected List<Product> load() {
                return shopCustomerService.findAllProducts();
            }
        };
    }

    private LoadableDetachableModel<List<Product>> loadProductModel(final Long categoryId) {
        return new LoadableDetachableModel<List<Product>>() {

            @Override
            protected List<Product> load() {
                ArrayList arrayList = new ArrayList(shopCustomerService.findCategoryById(
                        categoryId).getProducts());
                Collections.sort(arrayList);
                return arrayList;
            }
        };
    }

    @Override
    public IModel getPageTitle() {
        if (categoryId == null) {
            return new Model(getLocalizer().getString("eshop.title", this));
        }
        return new PropertyModel(categoryModel, "title");
    }

    @Override
    public IModel getDescription() {
        if (categoryId == null) {
            return new Model(getLocalizer().getString("eshop.description", this));
        }
        return new PropertyModel(categoryModel, "description");
    }

    @Override
    public IModel getKeywords() {
        if (categoryId == null) {
            return new Model(getLocalizer().getString("eshop.keywords", this));
        }
        return new PropertyModel(categoryModel, "keywords");
    }
}
